package com.yycwxt.modules.admin.file;

import com.yycwxt.common.ReturnResult;
import com.yycwxt.domain.File;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/files")
@Api
@Validated
public class FileController {
    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @GetMapping()
    @ApiOperation("查询全部文件清单")
    public ReturnResult selectAll() {
        return ReturnResult.buildSuccessResult(fileService.list());
    }

    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除文件清单")
    public ReturnResult deleteById(@ApiParam(name = "id的值", required = true, type = "String") @PathVariable String id) {
        try {
            Integer ids = Integer.valueOf(id);
            if (fileService.removeById(ids)) {
                return ReturnResult.buildSuccessResult(true);
            } else {
                return ReturnResult.buildFailureResult("id可能不存在", false);
            }
        } catch (Exception e) {
            return ReturnResult.buildFailureResult("id必须为数字", false);
        }
    }

    @PostMapping()
    @ApiOperation("添加一条文件清单")
    public ReturnResult insert(@ApiParam(name = "添加的数据", required = true, type = "File") @RequestBody @Validated File file) {
        try {
            return ReturnResult.buildSuccessResult(fileService.save(file));
        } catch (DuplicateKeyException dke) {
            return ReturnResult.buildFailureResult("name/id 值重复");
        } catch (Exception e) {
            return ReturnResult.buildFailureResult("参数错误");
        }
    }

    @PutMapping()
    @ApiOperation("根据id修改文件清单")
    public ReturnResult updateById(@ApiParam(name = "更改的数据", required = true, type = "File") @RequestBody @Validated File file) {
        try {
            if (fileService.updateById(file)) {
                return ReturnResult.buildSuccessResult(true);
            } else {
                return ReturnResult.buildFailureResult("id可能不存在或者name重复", false);
            }
        } catch (DuplicateKeyException dke) {
            return ReturnResult.buildFailureResult("name 值可能重复", false);
        } catch (Exception e) {
            return ReturnResult.buildFailureResult("参数错误");
        }
    }

    @GetMapping("/saleurl")
    @ApiOperation("获取销售统计相关文件URL")
    public ReturnResult getsaleurl(){
        return ReturnResult.buildSuccessResult(fileService.getsaleurl());
    }
}
